package db

import (
	"gitee.com/love_bass/go-utils/utils"
	"gopkg.in/yaml.v3"
	"gorm.io/gorm"
	"log"
	"os"
	"path/filepath"
)

const (
	DRIVER_MYSQL    = "mysql"
	DRIVER_POSTGRES = "postgres"
	DRIVER_SQLITE   = "sqlite"
)

type databaseConfig struct {
	Driver string `yaml:"driver"`
	MySQL  struct {
		Host     string `yaml:"host"`
		Port     int    `yaml:"port"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
		Database string `yaml:"database"`
	} `yaml:"mysql"`
	Postgres struct {
		Host     string `yaml:"host"`
		Port     int    `yaml:"port"`
		Username string `yaml:"username"`
		Password string `yaml:"password"`
		Database string `yaml:"database"`
	} `yaml:"postgres"`
	SQLite struct {
		Path string `yaml:"path"`
	} `yaml:"sqlite"`
}

var Context *gorm.DB
var config databaseConfig

func InitDatabase() {
	// 读取yaml文件
	data, err := os.ReadFile(filepath.Join(utils.LocalDir, "database.yaml"))
	if err != nil {
		log.Printf("数据库配置读取失败")
		log.Fatalf("无法读取yaml文件: %v", err)
	}
	// 将yaml文件的内容解析到结构体中
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		log.Printf("数据库配置读取失败")
		log.Fatalf("解析yaml文件失败: %v", err)
	}

	switch config.Driver {
	case DRIVER_MYSQL:
		initMySQL()
	case DRIVER_POSTGRES:
		initPostgres()
	case DRIVER_SQLITE:
		initSQLite()
	default:
		panic("Unsupported databaseConfig driver")
	}
}
